package com.longe.netty.protobufTwo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Random;

public class NettyProtoBufClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 当通道就绪时触发该方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        //随机的发送Student 或者 Teacher 对象
        int random = new Random().nextInt(3);
        MyMessageData.MyMessage myMessage = null;

        if(0 == random) { //发送Student 对象
            myMessage = MyMessageData.MyMessage.newBuilder()
                    .setDataType(MyMessageData.MyMessage.DataType.StudentType)
                    .setStudent(MyMessageData.Student.newBuilder().setId(5).setName("张三").build())
                    .build();
        } else { // 发送一个Teacher 对象
            myMessage = MyMessageData.MyMessage.newBuilder()
                    .setDataType(MyMessageData.MyMessage.DataType.TeacherType)
                    .setTeacher(MyMessageData.Teacher.newBuilder().setAge(20).setName("李四").build())
                    .build();
        }

        ctx.writeAndFlush(myMessage);
    }
}
